﻿
/*
<style type="text/css">
 .liss1{border-top:1px solid #dddddd;padding:5px 10px;}
 .liss2{background:#efefef;color:#c00;}
</style>

<input type="text" id="txtKeyWords" x-webkit-speech autocomplete="off" />
                
<script type="text/javascript"> 
lj_jq(function(){

        lj_jq("#txtKeyWords").autocomplete({
            zindex: 82282828282,
            //是否开启点击显示功能
            isClickAuto: false,
            "httpUrl": "/admin/area/default.aspx?cmd=5",
            "keyupFun": function () { },
            clickFun: function () {  }
        });
});
</script>
*/
lj_jq.fn.autocomplete = function (that) {
    that = lj_jq.extend({
        //当前对象
        obj: this,
        //默认提示容器
        DivDom: "#divTip",
        //默认离开样式
        moveOutClass: "liss1",
        //默认移上样式
        moveUpClass: "liss2",
        //远程提交查询页面
        httpUrl: "/Webform2.aspx",
        //默认远程提交参数
        ParameterName: "query",
        //查询的数据总条数
        DivLiCount: 10,
        //选择索引
        selectedIndex: -1,
        //搜索查询以及显示时间，时间越长，服务器压力越小
        autoSeachTime: 200,
        //是否开启点击显示功能
        isClickAuto: true,
        //是否开启点击选择功能
        isClickSelect: true,
        //点击输入框时提示信息的显示方式，false表示直接显示，true重新查询输入框中的关键词跟数据库
        ClickShowModlus: false,
        //执行回车事件
        enterFun: function () { },
        //每次弹起键盘时执行的方法
        keyupFun: function () {

        },
        //点击事件
        clickFun: function () { },
        //层级
        zindex: 9128873
    }, that);


    var keys = {
        ESC: 27,
        TAB: 9,
        RETURN: 13,
        UP: 38,
        DOWN: 40
    };

    //获取当前input的id属性
    this.id = lj_jq(this).attr("id");
    //外包围容器编号
    this.warpid = "wrap" + this.id;
    //提示框的编号
    this.tipid = "tip" + this.id;
    //是否已经存在有容器了？
    if (lj_jq("#" + this.warpid).length == 0) {
        //添加容器
        lj_jq(this).wrap("<div id='" + this.warpid + "' style='position:relative;color:#000;z-index:" + that.zindex + "'></div>");
        lj_jq(this).css({ "height": "20px", "padding": "0" });
        lj_jq("#" + this.warpid).prepend('<div style="display:none;background:#fff;border:2px solid #999;border-top:none;width:268px;position:absolute; top:40px; left:-12px;" id="' + this.tipid + '"><ul></ul><div>');
    }

    that.DivDom = '#' + this.tipid;

    that.DivObj = lj_jq(that.DivDom);

    if (window.opera) {
        this.bind('keypress', function (e) { autocompleteFun.onKeyPress(e); });
    } else {
        this.bind('keydown', function (e) { autocompleteFun.onKeyPress(e); });
    }

    this.bind("keyup", function (e) { that.keyupFun(); autocompleteFun.onKeyUp(e); });
    this.bind("blur", function (e) { autocompleteFun.onBlur(); });
    this.bind("click", function (e) {
        if (that.isClickAuto) {
            autocompleteFun.seach(e, that.ClickShowModlus);
        }

        //是否开启点击选择功能
        if (that.isClickSelect == true) {
            //是否开启点击显示功能
            that.isClickAuto = false;
        }
        that.clickFun();
    })

    var autocompleteFun =
    {
        //键盘按下时触发
        onKeyPress: function (e) {
            switch (e.keyCode) {
                case keys.ESC:
                    break;
                case keys.TAB:
                case keys.RETURN:
                    this.Enter();
                    break;
                case keys.UP:
                    this.moveUp();
                    break;
                case keys.DOWN:
                    this.moveDown();
                    break;
                default:
                    return;
            }

            e.stopImmediatePropagation();
            e.preventDefault();
        },
        Enter: function () {
            //执行回车事件
            that.enterFun(that.obj.val());
            //直接隐藏
            that.DivObj.hide();
            return;
        },
        onBlur: function () {
            //延迟隐藏，主要是在用鼠标选择需要值的时候使用。
            window.setTimeout(function () {
                //隐藏
                that.DivObj.hide();
            }, 200);
            return;
        },
        moveDown: function () {
            //累加索引，一直往下
            that.selectedIndex++;
            //索引值不能超过最大搜索数量
            if (that.selectedIndex >= that.DivLiCount) { that.selectedIndex = that.DivLiCount; }
            //添加当前选中样式,并删除其他选中样式
            that.DivObj.find("ul li:eq(" + that.selectedIndex + ")").addClass(that.moveUpClass).siblings().removeClass(that.moveUpClass);
            //把选中的内容赋值
            that.obj.val(that.DivObj.find("ul li:eq(" + that.selectedIndex + ")").attr("val"));
            return;
        },
        moveUp: function () {
            //递减索引，一直往上
            that.selectedIndex--;
            //不能超过最低数量
            if (that.selectedIndex < 0) { that.selectedIndex = 0; }
            //添加当前选中样式,并删除所有选中样式
            that.DivObj.find("ul li:eq(" + that.selectedIndex + ")").addClass(that.moveUpClass).siblings().removeClass(that.moveUpClass);
            //把选中的内容赋值
            var htm = that.DivObj.find("ul li:eq(" + that.selectedIndex + ")").attr("val");
            //赋值并获取焦点
            that.obj.val(htm).focus();
            return;
        },
        //键盘弹起后执行
        onKeyUp: function (e) {
            this.seach(e, true);
        },
        //搜索关键词  e:键盘值，isseach:是否进行数据库查询
        seach: function (e, isseach) {
            //搜索框中没有值时	    
            if (that.obj.val() == '') {
                //直接隐藏提示窗口
                that.DivObj.hide();
                //索引重置
                that.selectedIndex = -1;
                return false;
            }

            //是否需要进行数据库查询
            if (!isseach) {
                //直接显示元素
                that.DivObj.show();
                return true;
            }
            //防止重复提交多次
            window.clearTimeout(this.autoseach);
            //开始实现提交
            this.autoseach = window.setTimeout(function () {
                var keyword = stripscript(escape(that.obj.val()));
                if (keyword != '' && that.httpUrl != '' && e.keyCode != keys.UP && e.keyCode != keys.DOWN && e.keyCode != keys.RETURN && e.keyCode != keys.TAB && e.keyCode != keys.ESC) {

                    var typesjjksd = escape(lj_jq("#typevalue").html());
                    //组合传递参数
                    eval('var pars={"typevalue":"' + typesjjksd + '","' + that.ParameterName + '":"' + that.obj.val() + '"};');
                    lj_jq.ajax({
                        url: that.httpUrl, type: 'post',
                        data: pars,
                        //数据返回格式
                        //'sqe','seo','s司机','smc','smt','SPR','SAP','SPA','sj'
                        success: function (json) {
                            //清空显示区域
                            that.DivObj.find("ul").html('');
                            //显示
                            that.DivObj.show();

                            if (that.returnJson == undefined) {
                                //组合成json数据
                                eval("var jsonStr ={data: [" + json + "]}");
                                //获取json里面的数据长度
                                if (jsonStr.data.length > 0) {
                                    //循环遍历出所有数据
                                    for (var i = 0; i < jsonStr.data.length; i++) {

                                        //显示值
                                        var seachStr = autocompletePublic.formatResult(jsonStr.data[i], keyword);
                                        //真实值
                                        var txtWord = jsonStr.data[i].toLowerCase();
                                        //编号
                                        var liids = that.obj.attr("id") + "A" + i;
                                        //搜索框编号
                                        var seachId = that.obj.attr("id");
                                        //增加到显示
                                        that.DivObj.find("ul").append('<li class="' + that.moveOutClass + '" id="' + liids + '" val="'
								    + txtWord + '" onclick="autocompletePublic.clickLi(\'' + liids + '\',\''
                                    + that.DivDom + '\',\'' + seachId + '\',\'' + that.moveOutClass + '\',\''
                                    + that.moveUpClass + '\');" onmousemove="autocompletePublic.mousemove(\''
                                    + liids + '\',\'' + that.DivDom + '\',\'' + that.moveUpClass + '\');" >'
                                    + seachStr + '</li>');

                                    }
                                }
                            }
                            else {
                                //执行外部方法
                                that.returnJson(json);
                            }

                            //统计长度
                            that.DivLiCount = that.DivObj.find("ul li").length - 1;

                            if (that.DivLiCount == -1) {
                                that.DivObj.hide();
                            }

                        },
                        error: function (dat) { alert(dat); }
                    });
                }
            }, that.autoSeachTime);
            return true;
        } //seach
    };
}


var autocompletePublic = {
    formatResult: function (val, keyword) {
        val = val.toLowerCase();
        return val.replace(keyword, '<strong>' + keyword + '<\/strong>');
    },
    mousemove: function (liid, DivDom, moveUpClass) {
        lj_jq("#" + liid).addClass(moveUpClass).siblings().removeClass(moveUpClass);
    },
    clickLi: function (liid, DivDom, seachId, moveOutClass, moveUpClass) {
        var htm = lj_jq("#" + liid).attr("val");
        lj_jq("#" + seachId).val(htm).focus();
        lj_jq(DivDom).hide();
    }
}

function stripscript(s) {
    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]")
    var rs = "";
    for (var i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    return rs;
}
